<template>
  <div>
    <a-modal title="编辑SKU" :visible="visible" @before-open="open" @before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" top="20px" width="1100px" :mask-closable="false">
      <div>
        <div style="display: flex">
          <div class="left" style="width: 170px">
            <UplaodImg :style="{ width: '100%', height: '100%' }" @uploadSuccess="imgUploadSuccess" v-model="form.spuPic" :limit="1" />
          </div>
          <div class="right" style="flex: 1">
            <a-form auto-label-width ref="formRef" size="medium" :model="form">
              <a-row>
                <a-col :span="8">
                  <a-form-item label="SPU">
                    <a-input disabled v-model="form.spu" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="SKU">
                    <a-input disabled v-model="form.sku" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="产品类目">
                    <a-cascader :disabled="detail.type == 'edit'" @change="cateGoryChange" :check-strictly="false" :options="categoryOptions" :field-names="{ value: 'id', label: 'name' }" v-model="form.categoryId" placeholder="全部类目" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="产品开发员">
                    <a-select :disabled="detail.type == 'edit'" class="second" v-model="form.developerId" :max-tag-count="1" allow-search allow-clear placeholder="请选择">
                      <a-option :label="item.userName" :value="item.id" v-for="item of userList"></a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="开发部门">
                    <div>{{ $extract(form, 'developer.deptName') }}</div>
                    <!-- <a-input disabled v-model="form.developer.deptName" /> -->
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="产品名称">
                    <a-input v-model="form.skuName" />
                  </a-form-item>
                </a-col>

                <a-col :span="8">
                  <a-form-item label="重量（g）">
                    <a-input v-model="form.weight.weight" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="体积（cm）">
                    <a-space>
                      <a-input v-model="form.volume.length" placeholder="长" />
                      <a-input v-model="form.volume.width" placeholder="宽" />
                      <a-input v-model="form.volume.height" placeholder="高" />
                    </a-space>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="销售员">
                    <a-select v-model="form.salerIdList" multiple>
                      <a-option v-for="user of userList" :label="user.userName" :value="user.id"></a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="采购部门">
                    <a-select v-model="form.deptId">
                      <a-option v-for="item of deptList" :label="item.deptName" :value="item.id"></a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="备注">
                    <a-textarea placeholder="请输入" v-model="form.remark" />
                  </a-form-item>
                </a-col>
                <a-col :span="16">
                  <a-form-item label="标签">
                    <a-space wrap>
                      <div v-for="tag of form.tagList" class="tag-btn" :style="{ backgroundColor: tag.color }">{{ tag.name }}</div>
                      <a-tag class="cursor" color="arcoblue" size="small" bordered @click="tag.visible = true">添加标签</a-tag>
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
        <div v-if="specList.length > 0">
          <div class="title-bar">规格</div>
          <a-descriptions class="mt10 mb10" :data="specList" bordered />
        </div>
        <!-- <div class="title-bar">产品图</div> -->
        <a-tabs v-model:active-key="currentTab">
          <a-tab-pane title="产品图" :key="1">
            <AddSpuPic v-if="visible" :setFirtImg="setFirtImg" ref="addSpuPic" />
          </a-tab-pane>
          <a-tab-pane title="产品属性" :key="2">
            <ProductProperty ref="productProperty" type="edit" :propertyList="propertyList" />
          </a-tab-pane>
        </a-tabs>
      </div>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </div>

  <Tag ref="tag" @save="getTag" :list="form.tagList || []" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getOrganizesUser } from '@/api/system'
  import { productSKUDetail, updateProductSKUList, getPropTemplateByCateIdRec, findDeptList, skuUpdateBatchByIdV2 } from '@/api/product'
  import Tag from '../tag/tagList.vue'
  import AddSpuPic from './addSPu/addSpuPic.vue'
  import UplaodImg from '@/components/uploadImg.vue'
  import ProductProperty from './editSpu/productProperty.vue'
  export default defineComponent({
    props: ['detail', 'categoryOptions'],
    components: { Tag, AddSpuPic, UplaodImg, ProductProperty },
    setup(props: any, { emit }) {
      let visible = ref(false)
      const tag = ref()
      const formRef = ref()
      const addSpuPic = ref()
      const productProperty = ref()
      const data: any = reactive({
        currentTab: 1,
        form: {
          weight: {
            unit: 'g',
            weight: '',
          },
          volume: {
            height: '',
            length: '',
            unit: 'cm',
            width: '',
          },
        },
        rules: {
          warehouseCode: [{ required: true, message: '请选择发货仓' }],
        },
        loading: false,
        userList: [],
        specList: [],
        propertyList: [],
        deptList: [],
      })

      const open = () => {
        getUserList()
        getDetail()
        getDeptList()
        // data.form = props.detail.data
      }

      const getDeptList = async () => {
        const res: any = await findDeptList()
        data.deptList = res?.data || []
      }

      const setFirtImg = (list: any) => {
        data.form.spuPic = list[0]?.url || ''
      }

      const getDetail = async () => {
        const res: any = await productSKUDetail(props.detail.data.id)
        data.form = res?.data || {}
        if (data.form.salerList) {
          data.form.salerIdList = data.form.salerList.map((e: any) => e.id)
        }
        if (data.form.specValueList) {
          data.form.specValueList.forEach((e: any) => {
            let obj = { label: e.nameCn, value: e.valueCn }
            data.specList.push(obj)
          })
        }

        if (data.form.productPicList && data.form.productPicList[0]) {
          data.form.spuPic = data.form.productPicList[0].url
        }

        if (!data.form.volume) {
          data.form.volume = {
            height: '',
            length: '',
            unit: 'cm',
            width: '',
          }
        }

        if (!data.form.weight) {
          data.form.weight = {
            unit: 'g',
            weight: '',
          }
        }

        addSpuPic.value.init(data.form)
        data.form.categoryId = data.form?.category?.id || ''
        data.form.developerId = data.form?.developer?.id || ''
        if (data.form.category?.id) getProTem(data.form.category?.id)
        // 回显采购部门
        if (data.form.purchaseDeptList[0]) {
          data.form.deptId = data.form.purchaseDeptList[0].id
        }
      }

      const handleOk = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            let propList = productProperty.value.showValueList
            // 校验属性信息
            for (let i = 0; i < propList.length; i++) {
              const e = propList[i]
              let num = 0
              if (e.type == 8 || e.type == 7) {
                num = e.valueStrList.filter((e: any) => e).length
              }
              if (e.type == 1 && !e.valueStr && e.propRequired) {
                Message.error(`请选择${e.name}`)
                return false
              } else if (e.type == 2 && !e.valueStrList[0] && e.propRequired) {
                Message.error(`请选择${e.name}`)
                return false
              } else if (e.type == 4 && !e.valueStr && e.propRequired) {
                Message.error(`请选择${e.name}`)
                return false
              } else if (e.type == 5 && !e.valueNumber && e.propRequired) {
                Message.error(`请输入${e.name}`)
                return false
              } else if (e.type == 6 && !e.valueBigDecimal && e.propRequired) {
                Message.error(`请输入${e.name}`)
                return false
              } else if (e.type == 7 && num != 3 && e.propRequired) {
                Message.error(`请输入${e.name}`)
                return false
              } else if (e.type == 8 && num != 2 && e.propRequired) {
                Message.error(`请输入${e.name}`)
                return false
              }
            }

            let params = {
              ...data.form,
              productVideoList: addSpuPic.value.productVideoList,
              productAddPicList: addSpuPic.value.productAddPicList,
              productPicList: addSpuPic.value.productPicList,
              propList: propList,
            }

            if (data.form.spuPic) {
              let urlStr = ''
              data.form.spuPic instanceof Array ? (urlStr = data.form.spuPic[0].url) : (urlStr = data.form.spuPic)
              let index = params.productPicList.findIndex((e: any) => e.url == urlStr)
              if (index == -1) params.productPicList.unshift({ url: urlStr })
            }

            if (params.deptId) {
              let item = data.deptList.find((e: any) => e.id == params.deptId)
              if (item) {
                let arr = [{ name: item.deptName, id: item.id }]
                params.purchaseDeptList = arr
              }
            }

            try {
              data.loading = true
              // const res: any = await updateProductSKUList([params])
              const res: any = await skuUpdateBatchByIdV2([params])
              Message.success('编辑成功')
              handleCancel()
              emit('save')
            } catch (error) {}
            data.loading = false
          }
        })
      }

      const getUserList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        data.userList = res?.data?.records
      }

      const handleCancel = () => {
        data.currentTab = 1
        formRef.value.resetFields()
        formRef.value.clearValidate()
        data.specList = []
        visible.value = false
      }

      const getTag = (list: any) => {
        data.form.tagList = list
      }

      const imgUploadSuccess = () => {
        console.log(data.form.spuPic)

        addSpuPic.value.productPicList.push({ url: data.form.spuPic })
      }

      // 获取属性模板
      const getProTem = async (id: string) => {
        data.propertyList = []
        let params = {
          pageNum: 1,
          pageSize: 9999,
          categoryId: id,
        }
        const res: any = await getPropTemplateByCateIdRec(params)
        data.propertyList = res.data?.itemList ? res.data?.itemList : []
        productProperty.value.init(data.form.propList || [], data.propertyList || [])
      }

      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
        tag,
        getTag,
        addSpuPic,
        setFirtImg,
        imgUploadSuccess,
        productProperty,
      }
    },
  })
</script>

<style lang="less" scoped>
  :deep(.arco-upload-picture-card) {
    width: 160px;
    height: 160px;
  }
  :deep(.arco-upload-list-picture) {
    width: 160px;
    height: 160px;
  }

  .tag-btn {
    height: 20px;
    // min-width: 80px;
    line-height: 20px;
    padding: 0 5px;
    color: white;
    // margin-right: 5px;
    margin-bottom: 5px;
  }
</style>
